// LoginManager.cpp: implementation of the LoginManager class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "CommClientLib.h"
#include "LoginManager.h"
#include "CommWithServer.h"

#include "CommonLib\Structure.h"
#include "CommonLib\Packet.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

LoginManager::LoginManager()
{

}

LoginManager::~LoginManager()
{

}

LoginManager * LoginManager::m_pInstance = NULL;

LoginManager * LoginManager::Instance()
{
  if (m_pInstance == NULL)
  {
    m_pInstance = new LoginManager;
  }

  return m_pInstance;
}

void LoginManager::DeleteInstance()
{
  if (m_pInstance != NULL) delete m_pInstance;

  m_pInstance = NULL;
}

int LoginManager::Login(const CString& strServerIPAddress, int nPort, int nNetworkMode, LoginStruct * pLoginStruct)
{
  CommWithServer * pServer = CommWithServer::Instance();
  if (!pServer->Connect(strServerIPAddress, nPort))
  {
    return VCS_MR_FAILTOCONNECT;
  }

  pLoginStruct->m_dwMethodType = VCS_MT_LOGIN_EX;

  Packet packetReq(sizeof(LoginStruct), (LPBYTE)pLoginStruct);

  Packet packetAck;
  if ((packetAck.m_dwId = pServer->SendRequest(packetReq)) == 0)
  {
    pServer->Disconnect();
    return VCS_MR_FAILTOREQUEST;
  }
  if (!pServer->Receive(packetAck))
  {
    pServer->Disconnect();
    return VCS_MR_FAILTOACK;
  }

  memcpy(pLoginStruct, (LoginStruct *)packetAck.GetpData(), sizeof(LoginStruct));

  if (pLoginStruct->m_nMethodAck != VCS_MR_OK)
  {
    pServer->Disconnect();
    return VCS_MR_FAILTOLOGIN;
  }

  return VCS_MR_OK;
}

int LoginManager::Logout(const CString& strUserName)
{
  LoginStruct * pLoginStruct = new LoginStruct;
  pLoginStruct->m_dwMethodType = VCS_MT_LOGOUT;
  ASSERT(strUserName.GetLength() < sizeof(pLoginStruct->m_szUserId));
  strcpy(pLoginStruct->m_szUserId, strUserName);

  CommWithServer * pServer = CommWithServer::Instance();

  Packet packetReq(sizeof(LoginStruct), (LPBYTE)pLoginStruct);

  delete pLoginStruct;

  Packet packetAck;
  if ((packetAck.m_dwId = pServer->SendRequest(packetReq)) == 0)
  {
    pServer->Disconnect();
    return VCS_MR_FAILTOREQUEST;
  }
  if (!pServer->Receive(packetAck))
  {
    pServer->Disconnect();
    return VCS_MR_FAILTOACK;
  }

  if (!pServer->Disconnect())
  {
    return VCS_MR_FAILTODISCONNECT;
  }

  pLoginStruct = (LoginStruct *)packetAck.GetpData();
  return pLoginStruct->m_nMethodAck;
}
